package com.ruoyi.notice.service.send;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.notice.model.result.HandleMsgResult;
import com.ruoyi.notice.model.result.SendMsgResult;
import com.ruoyi.notice.service.ISendMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WeiXinQiYeSendMsgService implements ISendMessageService {

    private static final String REQUEST_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bf522f4d-b7db-40dc-899b-b874b7b20016";

    @Override
    public SendMsgResult toSendMessage(HandleMsgResult handleMsgResult){

        JSONObject bizMap = new JSONObject();
        bizMap.put("content", handleMsgResult.getContent());
        if (ObjectUtil.isNotEmpty(handleMsgResult.getUserInfoList())){
            bizMap.put("mentioned_list", handleMsgResult.getUserInfoList());
        }

        JSONObject paramMap = new JSONObject();
        paramMap.put("msgtype", "text");
        paramMap.put("text", bizMap);

        log.info("【微信群通知】开始发送【requestUrl】{}【paramMap】{}", REQUEST_URL, JSON.toJSONString(paramMap));
        String response = HttpUtil.createPost(REQUEST_URL)
                                .header("Content-Type", "application/json")
                                .body(JSON.toJSONString(paramMap))
                                .execute().body();
        log.info("【微信群通知】结束发送【response】{}", response);
        /**
         * {"errcode":0,"errmsg":"ok"}
         */
        JSONObject jsonObject = new JSONObject();
        String errcode = jsonObject.getString("errcode");
        String errmsg = jsonObject.getString("errmsg");

        SendMsgResult sendMsgResult = new SendMsgResult();
        sendMsgResult.setSuccess(false);
        sendMsgResult.setCode(errcode);
        sendMsgResult.setMessage(errmsg);
        sendMsgResult.setParamInfo(JSON.toJSONString(paramMap));
        sendMsgResult.setResultInfo(response);
        if (StrUtil.equals(errcode, "0")){
            sendMsgResult.setSuccess(true);
        }
        return sendMsgResult;
    }




}
